
import type { Plugin } from 'vite';
import fs from 'node:fs'
import path from 'node:path'

type PluginOptions = {
    base: string
}

export type RouteOptions = {
    name?: string,
    path?: string,
    component?: string,
    children?: RouteOptions[]
}
function autoRouter(options: PluginOptions): Plugin {
    return {
        name: 'vite-plugin-auto-router',
        enforce: 'post',
        configResolved(config:any){
            // config.command === 'serve' → 只在 vite serve / npm run dev
            console.log(options.base)
            console.log('钩子',config)
        }
        // transform(code: string, id: string) {
        //     // 只执行一次
        //     if (id.endsWith('/src/main.ts')) {
        //         // 获取文件夹
        //         const filePath = path.resolve(options.base + '/router')
        //         const existRouter = fs.existsSync(filePath)
        //         if (!existRouter) {
        //             fs.mkdirSync(filePath)
        //             const fillPath = filePath + '/index.ts'
        //             // 根据src下views目录递归生成路由文件
        //             const routes = getRoutesByViews(options)
        //             const front = generateCode(routes)
        //             console.log(front)
        //             const code = `${front}`
        //             fs.writeFileSync(fillPath, code)
        //         }

        //         getRoutesByViews(options)
        //     }
        // }
    }
}

const generateCode = (routes: string) => {
    return `import { createRouter, createWebHistory } from 'vue-router';
import type {RouteRecordRaw} from 'vue-router';
const routes:RouteRecordRaw[] = ${routes};
export default createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
});
`
}
function readAllFilesSync(dir: string) {
    let results: any = []
    const list = fs.readdirSync(dir, { withFileTypes: true })
    list.forEach(entry => {
        const fullPath = path.join(dir, entry.name)
        if (entry.isDirectory()) {
            results = results.concat(readAllFilesSync(fullPath))
        } else if (entry.isFile()) {
            results.push(fullPath)
        }
    })
    return results
}
export interface MenuNode {
    name: string;               // 文件名或文件夹名
    path: string;               // 相对路径
    type: 'file' | 'folder';    // 类型
    children?: MenuNode[];      // 子节点
}



interface RouteNode {
    path: string
    name: string
    componentPath: string
    children?: RouteNode[]
}


export const generateRoutes = (paths: string[], options: PluginOptions)=>{
    console.log(paths)
    return '[]'
}

const getRoutesByViews = (options: PluginOptions) => {
    const views = readAllFilesSync(path.resolve(options.base + '/views'))
    // 生成路由配置
    const routeConfig = generateRoutes(views,options);
    console.log(routeConfig);
    return routeConfig
}

export default autoRouter;